/**
 * Created by admin on 2017/1/25.
 * 我的小路由
 */
(function (win, doc) {
  "use strict";
  function Router(option) {
    this.routes = option.routes;
    this.currentUrl = '';

    var ele = doc.querySelector(option.view);
    this.v = {
      ele: ele,
      data: ''
    };

    this._init();
  }

  Router.prototype._binEvent = function () {
    win.addEventListener('load', this.refresh.bind(this), false);
    win.addEventListener('hashchange', this.refresh.bind(this), false);
  };

  /**
   * todo 此方式只能让 id 在最后面。
   */
  Router.prototype.refresh = function () {
    var hash = win.location.hash;
    if (!hash) {
      win.location.hash = '/';
      return;
    }

    this.currentUrl = hash.match(/#([\/\w]*)/)[1];
    var mothod = this.routes[this.currentUrl];

    if (mothod) {
      mothod.bind(this)();
    } else {
      var param = this.currentUrl.split('/').slice(1);
      if (param.length <= 1) return;

      var id = param[param.length - 1];
      var trUrl = this.currentUrl.replace('/' + id, ':id');

      if (this.routes[trUrl]) {
        this.v.id = id;
        this.routes[trUrl].bind(this)();
      }
    }
  };

  Router.prototype._init = function () {
    this._binEvent();
  };

  Router.prototype.go = function (path, data) {
    win.location.hash = path;
    this.v.data = data;
  }

  win.Router = Router;
})(window, document);
